using System;
using System.Collections.Generic;
using System.Text;
using CKS.EBE.API;
using System.Diagnostics;
using Microsoft.SharePoint;
using System.Xml;

namespace CKS.EBE.WebControls
{
    // TODO: class is never used. do we need it?
    public class RelatedPosts : SingleListQuery
    {
        protected static string Condition = "<Eq><FieldRef Name=\"Categories\" /><Value Type=\"Text\">{0}</Value></Eq>";

        public RelatedPosts()
        {
            ListName = Localization.GetListName(Localization.BlogList.Posts, Web.Language);
        }

        protected override XmlDocument BuildDocument()
        {
            if (string.IsNullOrEmpty(Page.Request["id"]))
            {
                XmlDocument oDoc = new XmlDocument();
                oDoc.LoadXml("<rows/>");
                return oDoc;
            }

            return base.BuildDocument();
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (string.IsNullOrEmpty(Page.Request["id"])) return;

            try
            {
                SPList oList = Helper.GetListByFolderName(Web, Localization.GetListName(Localization.BlogList.Posts, Web.Language));
                SPListItem oPost = oList.GetItemById(int.Parse(Page.Request["id"]));

                ViewFieldsXML += "<FieldRef Name='Body'/><FieldRef Name='NumComments'/><FieldRef Name='PublishedDate'/><FieldRef Name='PostCategory'/><FieldRef Name='FileDirRef'/><FieldRef Name='BlogTitleForUrl'/><FieldRef Name='CategoriesAsText' Nullable='True' />";

                StringBuilder sb = new StringBuilder("<Where><And><Neq><FieldRef Name='ID'/><Value Type='Text'>" + Page.Request["id"] + " </Value></Neq>");

                List<string> catList = new List<string>();

                SPFieldLookupValueCollection oCats = (SPFieldLookupValueCollection)oPost["Categories"];

                if (oCats == null)
                {
                    RowLimit = 0;
                    return;
                }

                foreach (SPFieldLookupValue v in oCats)
                {
                    string sValue = v.LookupValue.ToLower();
                    if (sValue != "sharepoint" && sValue != "tips" && sValue != "wss") 
                        catList.Add(v.LookupValue);
                }

                string[] arTerms = catList.ToArray();

                if (arTerms.Length > 1)
                    AddOrCondition(sb, arTerms, 0);
                else
                    sb.Append(string.Format(Condition, arTerms[0]));

                sb.Append("</And></Where>");

                sb.Append("<OrderBy><FieldRef Name='PublishedDate' Ascending='FALSE'/></OrderBy>");

                QueryXML = sb.ToString();

                RowLimit = 10;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }

        protected void AddOrCondition(StringBuilder sb, string[] arTerms, int position)
        {
            sb.Append("<Or>");

            if ((position + 2) < arTerms.Length)
            {
                AddOrCondition(sb, arTerms, position + 1);
                sb.Append(string.Format(Condition, arTerms[position]));
            }
            else
            {
                sb.Append(string.Format(Condition, arTerms[position]));
                if ((position + 1) < arTerms.Length) sb.Append(string.Format(Condition, arTerms[position + 1]));
            }

            sb.Append("</Or>");
        }
    }
}
